//引入axios
import axios from "axios";

//引入nprogress
import nProgress from "nprogress";
import "nprogress/nprogress.css";

import store from "@/store";

//创建axios实例
const request = axios.create({
    baseURL: process.env.VUE_APP_API,
    timeout: 10000,
})

//添加请求拦截器
request.interceptors.request.use(
    //请求成功
    (config) => {
        //开启进度条
        nProgress.start()

        //每次请求之前添加临时标识
        const userTempId = store.state.user.userTempId
        config.headers.userTempId = userTempId

        //每次请求之前添加token
        const token = store.state.user.token
        config.headers.token = token

        return config
    },

    //请求失败
    (error) => {
        //关闭进度条
        nProgress.done()

        //返回失败的Promise实例
        return Promise.reject(error)

    }
)

//添加响应拦截器
request.interceptors.response.use(
    //响应成功
    (response) => {
        //关闭进度条
        nProgress.done()

        //响应成功返回数据
        if(response.data.code === 200){
            return response.data.data
        }else{
            //自己封装的失败信息
            return Promise.reject({message: response.data.message})
        }
    },

    //响应失败
    (error) => {
        //关闭进度条
        nProgress.done()

        //返回失败的Promise实例
        return Promise.reject(error)
    }
)

export default request